const PartnerSvcUrl = Utils.CurDomain.PartnerSvcUrl;
import certRegsApi from '../../../common/api/food/certregs.api.js'
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../common/api/file-request.js";
import doT from '../../../../vendor/template/doT.js';

const addrecevTemplate = doT.template($('#addrecev-template').text());

let _vm, addressindex = 0, editintentionCity, editintentionArr, checkSltrSupp = [], checkboxList = [], employeesList = []
let userInfo = JSON.parse(Utils.GetSessionStorage('SNLoginUserInfo'));//jwt的当前用户信息
const LICENSE_PLATE = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/;
const PHONE_VERIFICATION = /^1[3456789]\d{9}$/;
const weightreg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/;
let _page = {
    pageSize: 10,
    pageIndex: 0,
    totalPages: -1,
};
(function (window, document, $) {
    $(async function () {
        _vm = new Vue({
            el: "#addentryrgst-form",
            data() {
                return {
                    "company": {
                        "id": "",
                        "name": ""
                    },
                    "carNo": "",
                    "driverName": "",
                    "bizDate": moment(new Date()).format('YYYY-MM-DD'),
                    "driverPhone": "",
                    "sltrSupps": [],
                    "afltdSltrSupps": "",
                    "avgWeight": 0,
                    "regOrderNo": '',
                    noticeTime: moment(new Date()).format('YYYY-MM-DD HH:mm'),
                    "isEnterPen": false,
                    "penEntRegId": "",
                    "penEntRegBillNo": "",
                    "regStaffCode": "",
                    "regStaffName": "",
                    "smpCour": "",
                    "chInsp": "",
                    "remark": "",
                    "attaches": [],
                    images:[],
                    uploadCount: 0,
                    page: { ..._page },
                }
            }
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        await _initCommand()
        clickFun()
        _initcityPicker()
        uploadInit()
        _initSltrregs()
    });
    // 初始化数据
    const _initCommand = async () => {
        // 公司
        await certRegsApi.queryBaseOrgunitList('ooca', 10).then(res => {
            $('#company').select2({
                placeholder: '请选择公司...', //默认文字提示
                language: "zh-CN",//汉化
                allowClear: true,//允许清空
                data: res.map(item => {
                    return {
                        id: item.id,
                        text: `${item.name}(${item.numCode})`,
                        name: item.name
                    }
                }),
            });
            if (userInfo.coun?.indexOf('公司') != -1) {
                _vm.company.id = userInfo?.coui
                _vm.company.name = userInfo?.coun
                $('#company').setSelectValue(userInfo?.coui, userInfo?.coun)
                var saleOrgsinfo = cutstr(userInfo?.coun, 20); // 截取字符串
                $('#company').next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
            }
        });
        // 选择公司
        $('#company').on('select2:select', async function (e) {
            _vm.company.id = $('#company').select2('data')[0].id
            _vm.company.name = $('#company').select2('data')[0].name
            var data = e.params.data; // 获取选中项的数据
            var text = data.text; // 获取选中项的文本
            var saleOrgsinfo = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
        });

        // 代宰户
        $('#sltrSupp').select2({
            allowClear: true,
            language: "zh-CN",
            placeholder: '请选择代宰户...', //默认文字提示
            ajax: {
                url: `${Utils.CurDomain.PartnerSvcUrl}/sltrsupps/by/q`,
                dataType: 'json',
                type: 'GET',
                beforeSend: Utils.AjaxBeforeSend,
                data: function (params) {
                    return {
                        Status: true,
                        // SearchInfo: params.term,
                        PageSize: 10,
                        PageIndex: (params.page || 1) - 1,
                        ...(Utils.IsNotNull(params.term) ? { SearchInfo: params.term } : {})
                    };
                },
                cache: true,
                delay: 700,//等待用户输入完后的 在等700毫秒 进行搜索
                processResults: function (data, params) {
                    params.page = params.page || 1;
                    let _data = data.data.items.map(item => {
                        item.text = `${item.name}(${item.numCode})`;
                        return item;
                    });
                    return {
                        results: _data,// 后台返回的数据集
                        pagination: {
                            more: params.page < data.data.totalPages// 总页数为10，那么1-9页的时候都可以下拉刷新
                        }
                    };
                },
                "error": async function (xhr, textStatus, errorThrown) {
                    let errorInfo = await Utils.AjaxError(xhr, textStatus, errorThrown)
                    if (Utils.IsNotNull(errorInfo)) {
                        sltrMakeAjaxCall()
                    }
                }
                // minimumInputLength: 1,
            }
        });
        $('#sltrSupp').setSelectValue();
        // 选择代宰户
        $('#sltrSupp').on('select2:select', function (e) {
            let res = $('#sltrSupp').select2('data')[0];
            _vm.sltrSupps = [];
            _vm.sltrSupps.push({
                    "id": res?.id,
                    "name": res?.name,
                    "numCode": res?.numCode,
                    "phone": res?.phone
            })
            var data = e.params.data; // 获取选中项的数据
            var text = data.text; // 获取选中项的文本
            var saleOrgsinfo = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
        });

        // 登记人
        $('#regStaffCode').select2({
            allowClear: true,
            language: "zh-CN",
            placeholder: '请选择登记人...', //默认文字提示
            ajax: {
                url: Utils.CurDomain.EmployeeMgtUrl + `/emplrecds/by/q`,
                dataType: 'json',
                type: 'GET',
                beforeSend: Utils.AjaxBeforeSend,
                data: function (params) {
                    return {
                        Status: true,
                        // SearchInfo: params.term,
                        PageSize: 10,
                        PageIndex: (params.page || 1) - 1,
                        ...(Utils.IsNotNull(params.term) ? { SearchInfo: params.term } : {})
                    };
                },
                cache: true,
                delay: 700,//等待用户输入完后的 在等700毫秒 进行搜索
                processResults: function (data, params) {
                    params.page = params.page || 1;
                    let _data = data.data.items.map(item => {
                        item.id = item.numCode
                        item.text = `${item.name}(${item.numCode})`;
                        return item;
                    });
                    return {
                        results: _data,// 后台返回的数据集
                        pagination: {
                            more: params.page < data.data.totalPages// 总页数为10，那么1-9页的时候都可以下拉刷新
                        }
                    };
                },
                "error": async function (xhr, textStatus, errorThrown) {
                    let errorInfo = await Utils.AjaxError(xhr, textStatus, errorThrown)
                    if (Utils.IsNotNull(errorInfo)) {
                        sltrMakeAjaxCall()
                    }
                }
                // minimumInputLength: 1,
            }
        });
        $('#regStaffCode').setSelectValue();
        // 选择登记人
        $('#regStaffCode').on('select2:select', function (e) {
            let res = $('#regStaffCode').select2('data')[0];
            _vm.regStaffCode = res?.id;
            _vm.regStaffName = res?.name;
        });

        // 选择业务日期
        $('#search-date').on('click', function () {
            pick();
        });

        // 编辑 66
        let ids = getUrlKey("id")
        if (Utils.IsNotNull(ids)) {
            document.title = '生猪入场与宰前检验 - 编辑'
            await certRegsApi.getAnmlQtCertRegs(ids).then(res => {
                res.bizDate = moment(res.bizFormObj.bizDate).format('YYYY-MM-DD');
                Utils.SetRouterState('deliverDatas', res)
                JSON.stringify(Utils.SetSessionStorage("ids", ids))
                res.pigEntAndCheckCertEntries.map(item => {
                    item.seq = Number(item.seq) - 1
                });
                JSON.stringify(Utils.SetSessionStorage("getReceveEntry", res.pigEntAndCheckCertEntries))
            });
        }

        // 获取主表数据
        let getMainInfo = JSON.parse(Utils.GetSessionStorage("deliverDatas"));
        if (Utils.IsNotNull(getMainInfo)) {
            var companyName = cutstr(getMainInfo.company.name, 20); // 截取字符串
            if(Utils.IsNotNull(getMainInfo.sltrSupps)){
                var sltrSuppsName = cutstr(getMainInfo.sltrSupps[0].name, 20); // 截取字符串
                $(`#sltrSupp`).select2('val', getMainInfo.sltrSupps[0].id); // 假设您想根据ID设置选中值
                $(`#sltrSupp`).next('.select2-container').find('.select2-selection__rendered').text(sltrSuppsName);    
            }
            const propertiesToCopy = [
                "company","carNo","driverName","bizDate","driverPhone","sltrSupps","afltdSltrSupps",
                "avgWeight","regOrderNo","noticeTime","isEnterPen","penEntRegId","penEntRegBillNo","regStaffCode",
                "regStaffName","smpCour","chInsp","remark","attaches",
            ];
            propertiesToCopy.reduce((obj, prop) => {
                _vm[prop] = getMainInfo[prop];
            }, {});
            $(`#company`).select2('val', getMainInfo.company.id); // 假设您想根据ID设置选中值
            $(`#company`).next('.select2-container').find('.select2-selection__rendered').text(companyName);
            $('#regStaffCode').setSelectValue(getMainInfo.regStaffCode, `${getMainInfo.regStaffName}(${getMainInfo.regStaffCode})`);
            let afltdSltrSupps = getMainInfo.afltdSltrSupps;
            let afltdSltrSuppsName ='';
            if(Array.isArray(afltdSltrSupps)==true){
                afltdSltrSupps.forEach((item)=>{
                    afltdSltrSuppsName +='，'+item.name;
                })
                getMainInfo.afltdSltrSupps =afltdSltrSuppsName.substring(1,afltdSltrSuppsName.length);
            }
            $('#afltdSltrSupps').val(getMainInfo.afltdSltrSupps);
            _vm.afltdSltrSupps = getMainInfo.afltdSltrSupps;
            if (Utils.IsNotNull(getMainInfo.attaches)) {
                if(Array.isArray(getMainInfo.attaches)==true){
                    _images(getMainInfo.attaches.join(','));
                }else{
                    _images(getMainInfo.attaches);
                }
            }
        }
        
        // 获取分录数据
        let getReceveEntry = JSON.parse(Utils.GetSessionStorage("getReceveEntry"))
        if (getReceveEntry) {
            $('#recevEntries').empty().append(addrecevTemplate(getReceveEntry));
        }

        // 点击 新增分录
        $('#add-recevEntries').on("click", function (e) {
            // 存储数据
            storeSession();
            let index = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))?.length || 0;
            location.href = `../certregs/certregentry.html?index=${index}`;
        })
        // 点击 编辑分录
        $(document).on('click', '#recevEntries div[data-flag=table-click-edit-recev]', function () {
            // 存储数据
            storeSession();
            // 获取分录 否则 默认是0
            let index = $(this).data('index')
            location.href = `../certregs/certregentry.html?index=${index}&isEdit=true`;
        });
        // 点击 删除分录
        $(document).on('click', '#recevEntries div[data-flag=table-click-delete-recev]', function () {
            let seq = $(this).data('index')
            $.modal({
                autoClose: false,
                title: '删除提示',
                text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
                    <div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
                        <div>是否确认删除该分录?</div>
                    </div>`,
                buttons: [
                    {
                        text: "取消", className: "default", onClick: function () {
                            $.closeModal();
                        }
                    },
                    {
                        text: "确定", onClick: function () {
                            if(!getReceveEntry){
                                getReceveEntry = JSON.parse(Utils.GetSessionStorage("getReceveEntry"));
                            }
                            let datas = getReceveEntry.filter(item => item.seq != seq)
                            // 重新排序
                            let info = datas.map((item, index) => {
                                item.seq = index
                                return item
                            }) || []
                            // 赋值 
                            JSON.stringify(Utils.SetSessionStorage("getReceveEntry", info))
                            $('#recevEntries').empty().append(addrecevTemplate(info));
                            $.closeModal();
                        }
                    }
                ]
            });
        });

    }
    // 操作函数
    const clickFun = async () => {
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            window.sessionStorage.removeItem("getEntryInfo");
            window.sessionStorage.removeItem("deliverDatas");
            window.sessionStorage.removeItem("ids");
            location.href = `../certregs/certregslist.html?v=${Utils.GetTime()}`;
        });

        //取消，关闭弹框
        $(document).on('click', '#returnAddSaleOrders', function () {
            $('#pop').css('display', 'none');
            $('.show-box').css('display', 'none');
            $('.show-box').css({
                'bottom': '-6rem',
                'transition': 'all .ls ease-in'
            });
        });

        // 提交数据
        $('#informationSubmit').on("click", function (e) {
            let entries = JSON.parse(Utils.GetSessionStorage("getReceveEntry"))
            if (!Utils.IsNotNull(_vm.company.id)) {
                return $.toptip(`请选择公司!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.carNo)) {
                return $.toptip(`请输入车牌号!`, 'warning');
            }
            if (Utils.IsNotNull(_vm.carNo) && !_vm.carNo.match(LICENSE_PLATE)) {
                return $.toptip(`请输入正确的车牌号!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.driverName)) {
                return $.toptip(`请输入司机名称!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.driverPhone)) {
                return $.toptip(`请输入司机联系方式!`, 'warning');
            }
            if (Utils.IsNotNull(_vm.driverPhone) && !_vm.driverPhone.match(PHONE_VERIFICATION)) {
                return $.toptip(`请输入正确的电话号码!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.sltrSupps)) {
                return $.toptip(`请选择代宰户!`, 'warning');
            }
            if (!(/^\d+$/).test(_vm.regOrderNo)) {
                return $.toptip(`登记顺序号为非负整数!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.bizDate)) {
                return $.toptip(`请选择业务日期!`, 'warning');
            }
            if (!Utils.IsNotNull(entries)) {
                return $.toptip(`请添加分录信息!`, 'warning');
            }
            savetips()
        })
    }

    // 附件上传
    const uploadInit = () => {
        weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                // `this` 是轮询到的文件, `files` 是所有文件
                if (["image/jpg", "image/jpeg", "image/png"].indexOf(this.type) < 0) {
                    $.toptip('请上传图片', 'warning');
                    return false; // 阻止文件添加
                }
                if (this.size > 8 * 1024 * 1024) {
                    $.toptip('请上传不超过8M的文件', 'warning');
                    return false;
                }
                $.showLoading('上传中..');
                _vm.uploadCount = ++_vm.uploadCount;
                if (_vm.uploadCount == 3) {
                    $('.weui-uploader__input-box').hide();
                }
            },
            onQueued: function () {
                let formFile = new FormData();
                let upFiles = this;
                let file = publicFileDraw(this.name, _vm);
                if (file != false && file != undefined) {
                    formFile.append('apiobjfile', new window.File([this], file, { type: this.type }));
                    _uploadFileDraw(formFile, upFiles, _vm, file);
                }
                //确认提交
                $('.weui-dialog__btn').on('click', function () {
                    if ($(this)[0].innerHTML == '确认') {
                        $.showLoading('上传中...');
                        let fileName = sliceFileName(upFiles);
                        let newfile = publicFileDraw(fileName, _vm);
                        if (newfile != false && newfile != undefined) {
                            formFile.append('apiobjfile', new window.File([upFiles], newfile, { type: upFiles.type }));
                            _uploadFileDraw(formFile, upFiles, _vm, newfile);
                        }
                    }
                });
                return true;
            }
        });
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.images = _vm.images.filter(item => item.id != _id);
                            _vm.uploadCount = --_vm.uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.uploadCount == 3) {
                                $(".weui-uploader__input-box").hide();
                            } else {
                                $(".weui-uploader__input-box").show();
                            }
                        },
                        onCancel: function () {
                        }
                    });
                }
            });
        });
    }

    // 附件上传
    const _uploadFileDraw = (formFile, upFiles, _vm, newName) => {
        uploadFile(formFile).then(res => {
            if (res.isSucceed) {
                let _list = _vm.images;
                _list.push({
                    id: $("#uploaderFiles li").length,
                    imageId: res.data,
                    url: upFiles.url,
                    name: newName,
                });
                _vm.attaches.push(res.data);
                $("#uploaderFiles li").each(function (i) {
                    $(this).attr('data-id', _vm.images[i].id);
                    $(this).attr('data-image-id', _vm.images[i].imageId);
                    $(this).attr('data-name', _vm.images[i].name);
                    $(this).attr('data-suffix', _vm.images[i].type);
                    $(this).attr('data-url', _vm.images[i].url);
                    $(this).css({ 'background-image': `url(${_vm.images[i].url})` });
                });
                $('.weui-uploader__file-content').hide();
                $('.weui-uploader__file').removeClass('weui-uploader__file_status');
                $.hideLoading();
                $.closeModal();
            }
        }).catch(res => {
            $("#uploaderFiles li").eq($("#uploaderFiles li").length - 1).remove();
            _vm.uploadCount = --_vm.uploadCount;
            $.toptip(res.msg, 'error');
        }).finally(_ => {
            $.hideLoading();
            $.closeModal();
        });
    }
    // 编辑回写
    const _images = async (file) => {
        let _imag = file.split(',');
        if (_imag) {
            if (!uploader) {
                await uploadInit();
            }
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                await requestFilePath(_imag[i]).then(_res => {
                    let _list = _vm.images;
                    _list.push({
                        id: _sun,
                        url: _res.data,
                        imageId: _imag[i],
                    });
                    if (_res.isSucceed) {
                        let _li;
                        if (["jpg", "jpeg", "png", 'gif'].indexOf(_imag[i].suffix) < 0) {
                            _li = `<li class="weui-uploader__file"  data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                        } else {
                            _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;

                        }
                        $('#uploaderFiles').append(_li);
                    }
                });
            }
            if (_sun == 3) {
                $(".weui-uploader__input-box").hide();
            }
            _vm.uploadCount = _sun;
        }
    }

    // 初始化发货行政区划
    const _initcityPicker = () => {
        // 取消按钮
        $('#canvalBtn').on('click', function () {
            $('#maskback').css('display', 'none')
            document.body.style.overflow = 'scroll'
            document.body.style.position = 'relative'

        })
        // 确定按钮
        $('#determineBtn').on('click', function () {
            let selectArr = []
            $('#selectCity').find('.innerAddress').each((index, item) => {
                let selectAddresss = $(item).text()
                if (Utils.IsNotNull(selectAddresss) && selectAddresss != '请选择') {
                    selectArr.push(selectAddresss)
                }
            })

            let selectIdArr = []
            $('#selectCity').find('.adressId').each((index, item) => {
                let selectAddresssId = $(item).text()
                if (Utils.IsNotNull(selectAddresssId)) {
                    selectIdArr.push(selectAddresssId)
                }
            })
            if (!Utils.IsNotNull(selectArr[0])) {
                $.toptip(`请选择省!`, 'warning');
                return
            }
            else if (!Utils.IsNotNull(selectArr[1])) {
                $.toptip(`请选择市!`, 'warning');
                return
            }
            else if (!Utils.IsNotNull(selectArr[2])) {
                $.toptip(`请选择区县!`, 'warning');
                return
            }
            else {
                _vm.certTkt.dptrPlc = `${selectIdArr.join(';')}|${selectArr.join(';')}`
                let selectCity = selectArr.join('-')
                $('#intentionCity').val(selectCity)
                editintentionCity = selectCity
                $('#canvalBtn').click()
            }
        })
        // 点击灰色遮罩层
        $('#unimportmask').on('click', function () {
            $('#canvalBtn').click()
        })
        // 点击发货行政区划
        $('#search-intentionCity').on('click', function () {
            editintentionCity = $('#intentionCity').val() || []
            // 关闭键盘
            document.activeElement.blur();
            // body禁止滚动
            document.body.style.position = 'fixed'
            document.body.style.overflow = 'hidden'
            // 清空选择页面内容
            $('#intentionContain').children('div').eq(0).empty()
            $('.innerAddress,.adressId').text('')
            changeStyle(0)

            addressindex = 0
            getAddress('province', "e8wa").then(res => {
                if (Utils.IsNotNull(editintentionCity)) {
                    editintentionArr = editintentionCity.split('-')
                    let editaddress = res.filter(item => {
                        return item.name == editintentionArr[0]
                    })
                    if (Utils.IsNotNull(editaddress)) {
                        $(`#${editaddress[0].id}`).click()
                    }
                }
            })
            setTimeout(() => {
                $('#maskback').css('display', 'block')
            }, 200);
        })
        // 点击导航栏
        $('#selectCity').on('click', 'li', function () {
            editintentionArr = []
            $(this).addClass('activeStyle').siblings('li').removeClass('activeStyle')
            $(this).find('.uderline').addClass('underlineit')
            $(this).siblings('li').find('.uderline').removeClass('underlineit')
            addressindex = $(this).index()
            $('#intentionContain').children('div').eq(addressindex).css('display', 'block').siblings('div').css('display', 'none')
        })
        // 选择之后
        $(document).on('click', '.addressCon', async function () {
            let addressid = $(this).attr('id')
            let addressName = $(this).text()
            $('#selectCity').find('li').eq(addressindex).find('span').text(addressName)
            $('#selectCity').find('li').eq(addressindex).find('.adressId').text(addressid)

            $(this).addClass('activeStyle').siblings('div').removeClass('activeStyle')
            addressindex = addressindex + 1
            changeStyle(addressindex)
            $('#intentionContain').children('div').eq(addressindex).empty()
            $('#intentionContain').children('div').eq(addressindex).last().nextAll().empty()
            $('#selectCity').find('li').eq(addressindex).find('span').parent().last().nextAll().find('.innerAddress').text('')

            if (addressindex == 1) {
                getAddress('city', addressid).then(res => {
                    if (Utils.IsNotNull(editintentionArr) && Utils.IsNotNull(editintentionArr[1])) {
                        let editaddress = res.filter(item => {
                            return item.name == editintentionArr[1]
                        })
                        if (Utils.IsNotNull(editaddress)) {
                            $(`#${editaddress[0].id}`).click()
                        }
                    }
                })
                let nextNav = $('#selectCity').find('li').eq(addressindex + 1).find('span')
                if (Utils.IsNotNull(nextNav.text())) {
                    nextNav.text('')
                }
            }
            else if (addressindex == 2) {
                getAddress('district', addressid).then(res => {
                    if (Utils.IsNotNull(editintentionArr) && Utils.IsNotNull(editintentionArr[2])) {
                        let editaddress = res.filter(item => {
                            return item.name == editintentionArr[2]
                        })
                        if (Utils.IsNotNull(editaddress)) {
                            $(`#${editaddress[0].id}`).click()
                        }
                    }
                })
            }
            else if (addressindex == 3) {
                getAddress('street', addressid).then(res => {
                    if (Utils.IsNotNull(editintentionArr) && Utils.IsNotNull(editintentionArr[2])) {
                        let editaddress = res.filter(item => {
                            return item.name == editintentionArr[3]
                        })
                        if (Utils.IsNotNull(editaddress)) {
                            $(`#${editaddress[0].id}`).click()
                        }
                    }
                })
            }
            else if (addressindex > 3) {
                $('#selectCity').find('li').eq(3).find('span').text(addressName)
            }
        })
    }
    const changeStyle = (id) => {
        $('#selectCity').find('li').eq(id).find('span').text('请选择')
        $('#selectCity').find('li').eq(id).addClass('activeStyle').siblings('li').removeClass('activeStyle')
        $('#selectCity').find('li').eq(id).find('.uderline').addClass('underlineit')
        $('#selectCity').find('li').eq(id).siblings('li').find('.uderline').removeClass('underlineit')
    }
    // 获取地点 联动
    const getAddress = async (level, pid) => {
        return new Promise((resolve, reject) => {
            let addressQuery = {
                level: level,
                pid: pid
            }
            getDistory(addressQuery).then(res => {
                let addressData = [...res]
                $('#intentionContain').children('div').eq(addressindex).css('display', 'block').siblings('div').css('display', 'none')
                addressData.forEach(item => {
                    $('#intentionContain').children('div').eq(addressindex).append(`<div class="addressCon" id="${item.id}" style="margin-bottom:8px">${item.name}</div>`)
                })
                resolve(addressData)
            })
        })
    }

    //获取行政区划 
    const getDistory = (data) => {
        return new Promise((resolve, reject) => {
            $.ajax({
                "url": `${Utils.CurDomain.SubDataUrl}/districts/q?l=${data.level}&pid=${data.pid}`,
                "type": 'GET',
                "dataType": "json",
                "beforeSend": Utils.AjaxBeforeSend,
                "success": function (result) {
                    resolve(result.data)
                },
                "error": function (xhr, textStatus, errorThrown) {
                    Utils.AjaxError(xhr, textStatus, errorThrown)
                }
            });
        })
    }

    // 时间选择器
    const pick = () => {
        weui.datePicker({
            defaultValue: (moment(new Date()).format('YYYY-MM-DD')).split('-'),
            end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                _vm.bizDate = moment(new Date(value)).format('YYYY-MM-DD')
            }
        });
    }
    // 时间选择器
    function isWhichTime(data) {
        let years = [];
        let mouth = [];
        let date = [];
        let hours = [];
        let minite = [];
        if (!years.length && !mouth.length) {
            for (let i = 1889; i <= 2030; i++) {
                years.push({
                    label: i + "年",
                    value: i
                });
            }
        }
        if (!mouth.length) {
            mouth = costomDatePicker(mouth, 1, 13, "月")
        }
        if (!date.length) {
            date = costomDatePicker(date, 1, 32, "日")
        }
        if (!hours.length) {
            hours = costomDatePicker(hours, 0, 24, "时")
        }
        if (!minite.length) {
            minite = costomDatePicker(minite, 0, 60, "分")
        }

        weui.picker(years, mouth, date, hours, minite, {
            id: new Date(),//让每一个点击弹框得都有一个不一样得id，这样就避免了共用一个弹框得时候，打开得日期是上一次另外一个得日期回显
            defaultValue: [new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate(), new Date().getHours(), new Date().getMinutes(), new Date().getSeconds()],
            onConfirm: result => {
                //result 是数组，返回得是当前选中得数，如[{lable:'2019年,value:2019},{lable:'2月,value:2}，{lable:'2号,value:2}]
                if (result.length) {
                    //yyyy-mm-dd hh:mm:ss
                    let time = result[0].value + '-' + result[1].value + '-' + result[2].value + ' ' + result[3].value + ':' + result[4].value;
                    if (data == 'noticeTime') {
                        _vm.noticeTime = time
                    }
                    else {
                        _vm.certTkt.issueTime = time
                    }
                }
            }
        });
    }

    //自定义日期:月时分秒
    function costomDatePicker(years, startTime, endTime, str) {
        for (let j = startTime; j < endTime; j++) {
            years.push({
                label: ('' + j).length === 1 ? '0' + j + str : '' + j + str,
                value: ('' + j).length === 1 ? '0' + j : '' + j,
            });
        }
        return years;
    };

    // 保存
    const savetips = () => {
        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style = "margin-top:-5px" >
                    <div class="addedientry" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;"><div class="addentry">是否确认保存该单据？</div></div></div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "确定", onClick: function () {
                        $.closeModal();
                        const propertiesToCopy = [
                            "company","carNo","driverName","bizDate","driverPhone","sltrSupps","afltdSltrSupps",
                            "avgWeight","regOrderNo","noticeTime","isEnterPen","penEntRegId","penEntRegBillNo","regStaffCode",
                            "regStaffName","smpCour","chInsp","remark","attaches",
                        ];
                        const datas = propertiesToCopy.reduce((obj, prop) => {
                            obj[prop] = _vm[prop];
                            return obj;
                        }, {});
                        let newafsltr = [];
                        let selectafsltr = datas.afltdSltrSupps;
                        if (Utils.IsNotNull(selectafsltr)) {
                            // 使用中文字符的逗号进行替换
                            let newStr = selectafsltr.replace(/，/g, ',');
                            // 直接使用map方法生成新数组
                            newafsltr = newStr.split(',').map((item) => ({
                                "id": '',
                                'name': item,
                                'numCode': ''
                            }));
                        }
                        datas.afltdSltrSupps = [...newafsltr]
                        let _attaches = [];
                        $.each(_vm.images, function (i, v) {
                            _attaches.push(v.imageId);
                        });
                        datas.attaches = _attaches.join(',')
                        let ids = Utils.GetSessionStorage("ids")
                        let entries = JSON.parse(Utils.GetSessionStorage("getReceveEntry")) || [];
                        if(entries.length > 0 ){
                            entries.forEach((item) => {
                                item.certTktDptrPlc = item.certTktDptrPlc.replace(/-/g, '');                                
                                if(Utils.IsNotNull(item.address)){
                                    item.certTktDptrPlc = item.certTktDptrPlc + item.address ;
                                }
                            })
                        } 
                        // 重新赋值
                        entries.map(item => item.seq = Number(item.seq) + 1);
                        datas.pigEntAndCheckCertEntries = [...entries];
                        if (Utils.IsNotNull(ids)) {
                            certRegsApi.putAnmlQtCertRegs(ids, datas).then(res => {
                                $.toptip('请求成功!', 'success');
                                setTimeout(function () {
                                    window.sessionStorage.removeItem("getReceveEntry");
                                    window.sessionStorage.removeItem("deliverDatas");
                                    window.sessionStorage.removeItem("ids");
                                    location.href = `./certregslist.html `;
                                }, 1000);
                            }, err => {
                                $.toptip(err.responseJSON?.msg, 'error');
                            });
                        }
                        else {
                            certRegsApi.postAnmlQtCertRegs(datas).then(res => {
                                $.toptip('请求成功!', 'success');
                                setTimeout(function () {
                                    window.sessionStorage.removeItem("getReceveEntry");
                                    window.sessionStorage.removeItem("deliverDatas");
                                    window.sessionStorage.removeItem("ids");
                                    location.href = `./certregslist.html `;
                                }, 1000);
                            }, err => {
                                $.toptip(err.responseJSON?.msg, 'error');
                            });
                        }
                    }
                }
            ]
        });
    }
    // 获取地址栏的 参数 
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }
    // 初始换代宰户
    const _initSltrregs = () => {
        // 点击代宰户 显示选择页面
        $(document).on('click', "#reportLead", function () {
            $("#report-contact").popup();
            $("#content").empty();
            refreshQuery();
        });
        //TODO : 员工上拉加载
        $("#iscroll").infinite().on("infinite", function () {
            let _data = _vm._data.page;
            if (_data.pageIndex == _data.totalPages) return;
            let self = this;
            if (self.loading) return;
            self.loading = true;
            setTimeout(function () {
                queryEmployeesList();
                self.loading = false;
            }, 500);   //模拟延迟
        });
        // 搜索
        $("#searchdiv form").submit(function () {
            _mainSearch();
            return false;
        }).on("input propertychange", Utils.throttle(_mainSearch, 500));
        search();
        // 搜索
        $("#searchdiv form").submit(function () {
            _mainSearch();
            return false;
        }).on("input propertychange", Utils.throttle(_mainSearch, 500));
        search();

        // 选择代宰户 复选框
        $(document).on('click', '#iscroll .weui-check__label', function (event) {
            // event.stopPropagation();   //表示阻止向父元素冒泡
            event.preventDefault();     //阻止 方法阻止元素发生默认的行为（例如，当点击提交按钮时阻止对表单的提交或者a标签）
            let isChecked = $(this).find("input[type='checkbox']").is(':checked')
            $(this).find("input[type='checkbox']").prop("checked", !isChecked);
            if (!isChecked == true && checkboxList.includes($(this).data("id")) == false) {
                checkboxList.push($(this).data("id"));
            } else {
                checkboxList.splice(checkboxList.indexOf($(this).data("id")), 1);
            }
            $('#subEmployees').text(`确定(${checkboxList.length})`);
            $("#choose").text(`已选择:${checkboxList.length}条`);
        });

        // 取消按钮
        $("#cancelSub").on('click', function () {
            let checkHistory = [...checkSltrSupp.map(item => { return item.id })] || [];// 点取消时的上一次数据
            checkboxList = checkHistory;// 上一次点 确定的数据  赋值给  选中的数据
            $('#subEmployees').text(`确定(${checkboxList.length})`);
            $("#choose").text(`已选择:${checkboxList.length}条`);
            $.closePopup();
            $('#searchInput').val("");
            $('#searchBar').removeClass("weui-search-bar_focusing");
        });

        // 确定
        $("#subEmployees").on('click', function () {
            let subData = [...checkboxList.map(item => { return [...employeesList, ...checkSltrSupp].find(item1 => item1.id == item); })] || [];
            checkSltrSupp = subData;
            $('#searchInput').val("");
            if (Utils.IsNotNull(checkSltrSupp.length)) {
                $('#reportLead').val(`已选择${checkSltrSupp.length}个代宰户`)
            }
            else {
                $('#reportLead').val('')
            }
            $.closePopup();
            $('#searchBar').removeClass("weui-search-bar_focusing");
        });
    }
    //查询代宰户信息
    const refreshQuery = () => {
        let _page = {
            "searchInfo": $('#searchInput').val(),
            "pageIndex": 0,
            "totalPages": -1,
            "pageSize": 50,
        };
        _vm.page = Object.assign(_vm.page, _page);
        queryEmployeesList();
    }

    function unique(arr) {
        const res = new Map();
        return JSON.parse(JSON.stringify(arr)).filter((a) => !res.has(a.id) && res.set(a.id, 1))
    }

    // 代宰户 输入框
    const _mainSearch = function () {
        let _page = {
            "searchInfo": $('#searchInput').val(),
            "pageIndex": 0,
            "totalPages": -1,
            "pageSize": 50,
        };
        _vm._data.page = Object.assign(_vm._data.page, _page);
        $("#content").empty();
        queryEmployeesList();
    };
    // 代宰户 输入框
    const search = () => {
        let $searchBar = $('#searchBar'),
            $searchResult = $('#searchResult'),
            $searchText = $('#searchText'),
            $searchInput = $('#searchInput'),
            $searchClear = $('#searchClear'),
            $searchForm = $('#searchForm'),
            $searchCancel = $('#searchCancel');

        function hideSearchResult() {
            $searchResult.hide();
            $searchForm.attr('aria-expanded', 'false');
            $searchInput.val('');
        }
        function cancelSearch() {
            hideSearchResult();
            $searchBar.removeClass('weui-search-bar_focusing');
            $searchText.show();
        }

        $searchText.on('click', function () {
            $searchBar.addClass('weui-search-bar_focusing');
            $searchInput.focus();
        });

        $searchInput
            .on('blur', function () {
                if (!this.value.length) cancelSearch();
            })
            .on('input', function () {
                if (this.value.length) {
                    $searchResult.show();
                    $searchForm.attr('aria-expanded', 'true');
                } else {
                    $("#content").empty();
                    //refreshQuery();
                    $searchResult.hide();
                    $searchForm.attr('aria-expanded', 'false');
                }
            });
        $searchClear.on('click', function () {
            hideSearchResult();
            $searchInput.focus();
            $("#content").empty();
            refreshQuery()
        });
        $searchCancel.on('click', function () {
            cancelSearch();
            $("#content").empty();
            refreshQuery();
            $searchInput.blur();
        });
    }

    //代宰户 数据源
    const queryEmployeesList = () => {
        let _data = _vm.page;
        let _list = [];
        certRegsApi.getsltrSupp(Object.assign({
        }, _data)).then(res => {
            let _page = {
                searchInfo: $('#searchInput').val(),
                pageSize: 50,
                pageIndex: _data.pageIndex + 1,
                totalPages: res.totalPages,
            }
            _vm._data.page = Object.assign({}, _page);
            if (!Utils.IsNotNull($('#searchInput').val()) && _data.pageIndex == 0) {
                _list.push(...checkSltrSupp);
            }
            _list.push(...res.items);
            unique(_list).map(item => {
                let labhtml = `<label class="weui-cell weui-cell_active weui-check__label" for="${item.id}" data-id="${item.id}" id="lab_${item.id}">
                    <div class="weui-cell__hd">
                        <input type="checkbox" class="weui-check" name="checkbox1" id="${item.id}">
                        <i class="weui-icon-checked"></i>
                    </div>
                    <div class="" aria-hidden="true">
                        <span>名称：${item.name}</span>
                        <div>编码：${item.numCode}</div>
                    </div>
                    </div>
                </label>`
                $("#content").append(labhtml);
            });
            checkboxList.map(item1 => $(`#${item1}`).prop("checked", true));
            employeesList = [...employeesList, ...res.items];
        });
    }

    // 保存分录以上的内容
    const storeSession = () => {
        const propertiesToCopy = [
            "company","carNo","driverName","bizDate","driverPhone","sltrSupps","afltdSltrSupps",
            "avgWeight","regOrderNo","noticeTime","isEnterPen","penEntRegId","penEntRegBillNo","regStaffCode",
            "regStaffName","smpCour","chInsp","remark","attaches",
    ];
        const deliverDatas = propertiesToCopy.reduce((obj, prop) => {
            obj[prop] = _vm[prop];
            return obj;
        }, {});
        Utils.SetRouterState('deliverDatas', deliverDatas)
    }

    

})(window, document, jQuery)


